package com.hlkj.warboot.module_wx.controller;

import java.nio.charset.StandardCharsets;
import java.text.MessageFormat;
import java.util.UUID;
import java.util.Map;
import java.util.HashMap;
import java.util.Formatter;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @Description JsapiTicket签名
 * @Author lixing
 * @Date 2021/3/9 21:40
 */
public class WeChatSignForJsapiTicket {
    public static void main(String[] args) {
//        String jsapi_ticket = "jsapi_ticket";
//        // 注意 URL 一定要动态获取，不能 hardcode
//        String url = "http://example.com";
//        Map<String, String> ret = sign(jsapi_ticket, url);
//        ret.entrySet().stream().map(entry -> entry.getKey() + ", " + entry.getValue()).forEach(System.out::println);
    }

    public static Map<String, String> sign(String jsapiTicket, String url) {
        Map<String, String> ret = new HashMap<String, String>();
        String nonceStr = createNonceStr();
        String timestamp = createTimestamp();
        String string1;
        String signature = "";

        //注意这里参数名必须全部小写，且必须有序
        string1 = MessageFormat.format("jsapi_ticket={0}&noncestr={1}&timestamp={2}&url={3}",jsapiTicket,nonceStr,timestamp,url);
        try {
            MessageDigest crypt = MessageDigest.getInstance("SHA-1");
            crypt.reset();
            crypt.update(string1.getBytes(StandardCharsets.UTF_8));
            signature = byteToHex(crypt.digest());
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        ret.put("jsapi_ticket", jsapiTicket);
        ret.put("nonceStr", nonceStr);
        ret.put("timestamp", timestamp);
        ret.put("url", url);
        ret.put("signature", signature);
        return ret;
    }

    private static String byteToHex(final byte[] hash) {
        Formatter formatter = new Formatter();
        for (byte b : hash) {
            formatter.format("%02x", b);
        }
        String result = formatter.toString();
        formatter.close();
        return result;
    }

    private static String createNonceStr() {
        return UUID.randomUUID().toString();
    }

    private static String createTimestamp() {
        return Long.toString(System.currentTimeMillis() / 1000);
    }
}
